package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDto;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVo;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVo;
import cn.tedu._05weibo.pojo.vo.WeiboVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
@Validated
@Api(tags = "02.微博模块")
@Slf4j
@RestController
@RequestMapping(value = "/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    /**
     * 发布微博功能
     */
    @PostMapping("insert")
    @ApiOperation(value = "发布微博功能")
    public JsonResult insert(@RequestBody WeiboDto weiboDto, @ApiIgnore HttpSession session){
        /*
            1.校验用户登录状态
                1.1未登录状态：retur 2;
                1.2登录状态：插入数据接口，return 1;
         */
        log.debug("weiboDto = " + weiboDto);
        UserVo userVo = (UserVo) session.getAttribute("user");
        if (userVo == null){//未登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDto,weibo);
        weibo.setUserId(userVo.getId());
        weibo.setCreated(new Date());
        weiboMapper.insert(weibo);
        return JsonResult.ok();
    }
    /**
     * 2.微博首页功能
     */
    @GetMapping("selectIndex")
    @ApiOperation(value = "微博首页功能")
    public JsonResult selectIndex(WeiboVo weiboVo){
        List<WeiboVo> list = weiboMapper.selectIndex(weiboVo);
        return JsonResult.ok(list);
    }
    /**
     * 3.微博详情功能
     */
    @GetMapping("selectById")
    @ApiOperation(value = "微博详情页功能")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "微博ID",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "username",value = "用户名",required = true,dataType = "String")
    })

    public JsonResult selectById(@Range(min = 200, max = 300, message = "微博ID必须在200-300之间")@RequestParam Long id, String username){
        //手动抛出异常
        if (id<0) {
            throw new IllegalArgumentException("ID值不能小于0");
        }
        //username是为了演示knif4j的注解，没有任何用
        WeiboDetailVo weiboDetailVo = weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVo);
    }

}
